#include <stdio.h>
#include <stdlib.h>
#include <string.h>  
#include "STACK.h"


PLinkStack createNullStack_link()
{
    PLinkStack stack = (PLinkStack)malloc(sizeof(struct LinkStack));
    if(stack == NULL)
        return NULL;
    
    stack->top = NULL;
    return stack;
}

void deepCopyEditAction(EditAction *dest, const EditAction *src)
{
    dest->operation = src->operation;
    dest->line = src->line;
    
    dest->oldText = src->oldText ? strdup(src->oldText) : NULL;
    dest->newText = src->newText ? strdup(src->newText) : NULL;
}

void freeEditActionStrings(EditAction *action)
{
    if (action->oldText) {
        free(action->oldText);
        action->oldText = NULL;
    }
    if (action->newText) {
        free(action->newText);
        action->newText = NULL;
    }
}

int Push_LinkStack(PLinkStack L, EditAction *action)
{
    if (L == NULL || action == NULL) 
    {
        return -1;
    }
    PNode p = (PNode)malloc(sizeof(struct node));
    if (!p) return -1;
    
    deepCopyEditAction(&(p->info), action);
    
    p->link = L->top;
    L->top = p;
    return 1;
}

EditAction* Pop_LinkStack(PLinkStack L)
{
    if(L == NULL || L->top == NULL) 
        return NULL;
    
    PNode p = L->top; 
    EditAction* action = (EditAction*)malloc(sizeof(EditAction));
    if (!action) return NULL;
    
    deepCopyEditAction(action, &(p->info));
    
    L->top = p->link;
    
    freeEditActionStrings(&(p->info));
    free(p);
    return action;
}


void destroyStack_link(PLinkStack L)
{
    if(L == NULL)
        return;
    
    struct node *p = L->top;
    struct node *q;
    
    while(p != NULL)
    {
        q = p->link;
        freeEditActionStrings(&(p->info));
        free(p);
        p = q;
    }
    
    L->top = NULL;
}